<template>
    <div class="box">
      <el-empty style="width: 100%;" description="暂无数据" v-if="data.tableData.length === 0" />

        <div style="flex:1">
        <div class="list-box" v-for="(item,i) in data.tableData" :key="item.id">
            <div>
                <img style="width:200px;height: 200px;"  :src="imgList[i%5]" alt=""  @click="imgFn(item)"/>
                {{ item.name }}
            </div>
            
           
        </div>

        <el-dialog v-model="dialogTableVisible" :title="detail.name"  width="500px">
             <div class="box-card list-item">
                <div>状态：{{ detail.status }}</div>
                <div>开始时间：{{ formatDateTime(detail.startTime)}}</div>
                <div>技术时间：{{ formatDateTime(detail.endTime) }}</div>
                <div>描述：{{ detail.description }}</div>
                    <el-button class="button" type="success" @click="handleRegistration(detail.id)">报名</el-button>

            </div>
        </el-dialog>
      <!-- <div style="margin-top: 25px">
        <el-pagination
            @size-change="load"
            @current-change="load"
            v-model:current-page="data.currentPage"
            v-model:page-size="data.pageSize"
            :page-sizes="[5, 10, 15, 20]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total"
        />
      </div>  -->
    </div>


 

    <div class="ipt">
      <!-- <el-input style="width: 250px" v-model="data.name" placeholder="赛事名称" prefix-icon="Search"></el-input>
      <el-input style="width: 250px;" v-model="data.location" placeholder="赛事地点" prefix-icon="Search"></el-input>
     <div>
        <el-button type="primary" style="width: 50px;"  @click="loadByName">查询</el-button>
        <el-button type="success"  style="width: 50px;" @click="reset">重置</el-button>
     </div> -->
     <el-button class="button" type="success" style="width: 90px;" @click="loadByName('')">全部</el-button>
     <el-button class="button" type="success" style="width: 90px;" v-for="(item,i) in data.categories" :key="i" @click="loadByName(item.id)">{{ item.name }}</el-button>

    
    </div>
    </div>

    
        

  </template>

  <script setup>
  import {onMounted, reactive,ref} from "vue";
  import request from "@/utils/request";
  import { Delete, Edit, Search } from "@element-plus/icons-vue";
  import { ElMessage, ElMessageBox } from "element-plus";
  import dayjs from 'dayjs';
  import img1 from '@/assets/01.jpeg'
  import img2 from '@/assets/02.jpeg'
  import img3 from '@/assets/03.jpeg'
  import img4 from '@/assets/04.jpeg'
  import img5 from '@/assets/05.jpeg'
const imgList = [img1,img2,img3,img4,img5]

const detail = ref({})
const dialogTableVisible = ref(false)
const imgFn = (row) => {
    detail.value = row
    dialogTableVisible.value = true
}

  const data = reactive({
    name: '',
    location: '',
    categories:[],
    form: {},// 存储赛事类目列表
    tableData: [],
    currentPage: 1,
    pageSize: 999,
    total: 0,
    FormVisible: false,
    ids: [],
  });

  const userRole = ref(JSON.parse(localStorage.getItem('user')).role) 

  // 日期时间格式化函数
  const formatDateTime = (date) => {
    return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '--';
  };

  const loadByName = (id) => {
    data.currentPage = 1;
    load(id);
  };

  const load = (id) => {
    request.get('/evertInformation/SelectPage', {
      params: {
        pageNum: data.currentPage,
        pageSize: 999,
        categoryId: id  || ''
      }
    }).then(res => {
      data.tableData = res.data?.list || [];
      data.total = res.data?.total || 0;
    });
  };

  const reset = () => {
    data.name = '';
    data.location = '';
    load();
  };

  const hadleNewracer = () => {
    data.FormVisible = true;
    data.form = {
      status: 'UPCOMING'
    };
  };

  // 组件挂载时加载类目
  onMounted(() => {
    request.get('/eventCategory/listAll').then(res => {
      data.categories = res.data || [];
    });
  });

  const save = () => {

    // 1. 日期格式化
    const params = {
      ...data.form,
      startTime: data.form.startTime
          ? dayjs(data.form.startTime).format('YYYY-MM-DD HH:mm:ss')
          : null,
      endTime: data.form.endTime
          ? dayjs(data.form.endTime).format('YYYY-MM-DD HH:mm:ss')
          : null
    };

    // 2. 根据是否存在 id 判断是新增还是更新
    const isUpdate = !!data.form.id;
    const url = isUpdate
        ? `/evertInformation/updateEventInformation`  // 更新接口
        : `/evertInformation/addEventInformation`;         // 新增接口

    // 3. 统一请求方法
    const requestMethod = isUpdate ? request.put : request.post;

    // 4. 发送请求
    requestMethod(url, params).then(res => {
      if (res.code === '200') {

        // 获取刚保存的赛事ID（假设后端返回保存后的对象）
       // const eventId = res.data.id;

        ElMessage.success("操作成功");
        data.FormVisible = false;
        load(); // 刷新表格数据
      } else {
        ElMessage.error(res.msg);
      }
    }).catch(err => {
      ElMessage.error("请求失败：" + err.message);
    });
    // 确保日期格式正确
    // const params = {
    //   ...data.form,
    //   startTime: data.form.startTime ? dayjs(data.form.startTime).format('YYYY-MM-DD HH:mm:ss') : null,
    //   endTime: data.form.endTime ? dayjs(data.form.endTime).format('YYYY-MM-DD HH:mm:ss') : null
    // };
    //
    // const requestMethod = data.form.id ? request.put : request.post;
    // requestMethod('/evertInformation', params).then(res => {
    //   if (res.code === '200') {
    //     ElMessage.success("操作成功");
    //     data.FormVisible = false;
    //     load();
    //   } else {
    //     ElMessage.error(res.msg);
    //   }
    // });
  };

  const add = () => {
    request.post("/evertInformation/addEventInformation", data.form).then(res => {
      if (res.code === '200') {
        ElMessage.success("操作成功")
        data.FormVisible = false; //添加后 关闭对话框
        load()
      } else {
        ElMessage.error(res.msg)
      }

    })
  }


  const update = () => {

    request.put("/evertInformation/updateEventInformation/", data.form).then(res => {
      if (res.code === '200') {
        ElMessage.success("操作成功")
        data.FormVisible = false; //更新后 关闭对话框
        load()
      } else {
        ElMessage.error(res.msg)
      }

    })
  }

  const handleUpdate = (row) => {
    data.form = JSON.parse(JSON.stringify(row));
    data.FormVisible = true;
  };

  const handleDelete = (id) => {
    ElMessageBox.confirm('确定要删除该赛事吗？', '删除确认', { type: "warning" }).then(() => {
      request.delete(`/evertInformation/${id}`).then(res => {
        if (res.code === '200') {
          ElMessage.success("删除成功");
          load();
        }
      });
    }).catch(() => {});
  };
  const handleRegistration = (id) => {
    let userId = JSON.parse(localStorage.getItem('user')).id
    ElMessageBox.confirm('确定要报名该赛事吗？', '确认', { type: "warning" }).then(() => {
      request.post(`/Registration/addRegistrationInformation`,{
        eventId:id,
        userId:userId
      }).then(res => {
        if (res.code === '200') {
            dialogTableVisible.value = false;
          ElMessage.success("报名成功");
          load();
        }
      });
    }).catch(() => {});
  }
  const handleSelectionChange = (rows) => {
    data.ids = rows.map(row => row.id);
  };

  const deleteBatch = () => {
    if (data.ids.length === 0) {
      ElMessage.warning('请选择要删除的数据');
      return;
    }
    ElMessageBox.confirm('确定要删除选中数据吗？', '批量删除确认', { type: "warning" }).then(() => {
      request.delete('/evertInformation/batch', { data: data.ids }).then(res => {
        if (res.code === '200') {
          ElMessage.success("删除成功");
          load();
        }
      });
    }).catch(() => {});
  };

  // 初始化加载
  load();
  </script>

  <style scoped>
  .el-input {
    width: 300px;
  }
  .el-date-picker {
    width: 100%;
  }
  .list-box{
    /* width: 100%; */
    margin: 20px;
    display: inline-block;
    width: 200px;
}
  .list-item{
    height: 240px;
    line-height: 40px;
    width: 500px;

  }
    .box{

            display: flex;
        
    }

    .ipt{
        margin-bottom: 10px;
        width: 300px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        gap: 20px;
    }
    .button{
        margin: 0 !important;
    }
  </style>